package com.gwclh.personnel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gwclh.personnel.bean.ResultVo;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gwclh.personnel.domain.PageDomain;
import com.gwclh.personnel.entity.Department;
import com.gwclh.personnel.entity.Employee;
import com.gwclh.personnel.mapper.DepartmentMapper;
import com.gwclh.personnel.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gwclh.personnel.service.IEmployeeService;
import com.gwclh.personnel.vo.deptvo.DeptTreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author gzhhh
 * @since 2020-07-24
 */
@Service
@Slf4j
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    IEmployeeService employeeService;

    List<DeptTreeVo> localDeptTreeVos;

    @Override
    public ResultVo listDepartments(PageDomain pageDomain, Department department) {
        // 前端传送request，封装成pagedomain
        Page<Department> departmentPage = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        // 添加排序条件
        pageDomain.setSortColumn("id");
        departmentPage.addOrder(pageDomain.getOrderItemBy());
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();

        departmentQueryWrapper.like("dept_name", department.getDeptName());
        if (department.getDeptType() != null) {
            departmentQueryWrapper.eq("dept_type", department.getDeptType());
        }

        this.page(departmentPage, departmentQueryWrapper);

        List<Department> departments = departmentPage.getRecords();
        HashMap<String, Object> result = new HashMap<>();
        result.put("departments", departments);
        // log.info(String.valueOf(departments));
        result.put("total", departmentPage.getTotal());
        return ResultVo.success(result);
    }

    @Override
    public ResultVo insertDepartment(Department department) {
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.eq("dept_name", department.getDeptName());
//        Assert.isNull(this.getOne(departmentQueryWrapper), "该部门已存在");
//        System.out.println("pid"+department.getPId());
        Assert.isTrue(this.save(department), "添加部门失败");
        return ResultVo.success();
    }

    /**
     * 根据部门id删除部门
     *
     * @param id
     * @return
     */
    @Override
    public ResultVo delDept(Integer id) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", id);
        List<Department> departments = this.list(queryWrapper);
        if (departments.size() > 0) {
            return ResultVo.fail("该部门下存在子部门，删除失败");
        }
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
        employeeQueryWrapper.eq("dept_id", id);
        Integer countDeptId = employeeService.count(employeeQueryWrapper);
        if (countDeptId > 0) {
            return ResultVo.fail("该部门还有员工，删除失败");
        }
        Assert.isTrue(this.removeById(id), "删除部门失败");
        return ResultVo.success();
    }


    /**
     * 通过部门id构建该部门的部门树
     */
    public void buildDeptTreeByDeptId(DeptTreeVo deptTreeVo) {
        if (deptTreeVo.getpId() == 0) {
            this.localDeptTreeVos.add(deptTreeVo);
            return;
        } else {
            Department preDepartment = this.getOne(new QueryWrapper<Department>().eq("id", deptTreeVo.getpId()));
            DeptTreeVo preDeptTreeVo = new DeptTreeVo();
            BeanUtils.copyProperties(preDepartment, preDeptTreeVo);

            List<DeptTreeVo> deptTreeVos = new ArrayList<>();
            deptTreeVos.add(deptTreeVo);
            preDeptTreeVo.setChildren(deptTreeVos);

            this.buildDeptTreeByDeptId(preDeptTreeVo);
        }
    }


    @Override
    public ResultVo listDeptTree(Department department) {

        if(department.getId()!=null){
            localDeptTreeVos = new ArrayList<>();
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();

            departmentQueryWrapper.eq("id", department.getId());

            if (department.getDeptType() != null) {
                departmentQueryWrapper.eq("dept_type", department.getDeptType());
            }
            Department department1 = this.getOne(departmentQueryWrapper);
            if (department1 != null) {
                DeptTreeVo deptTreeVo = new DeptTreeVo();
                BeanUtils.copyProperties(department1, deptTreeVo); // 技术部Vo
                List<DeptTreeVo> deptTreeVos = new ArrayList<>();
                deptTreeVos.add(deptTreeVo);
                buildDeptTreeByDeptId(deptTreeVo);
            }
            return ResultVo.success(this.localDeptTreeVos);
        }else {
            //顶级部门列表
            List<Department> list = this.list(new QueryWrapper<Department>().eq("p_id", 0));
            //部门子树
            List<DeptTreeVo> deptTrees = new ArrayList<>();

            for (Department department1 : list) {
                DeptTreeVo deptTree = new DeptTreeVo();
                BeanUtils.copyProperties(department1, deptTree);
                deptTree.setChildren(getDeptTreeChildren(deptTree.getId()));
                deptTrees.add(deptTree);
            }
            return ResultVo.success(deptTrees);
        }

    }

    //获取部门子部门
    public List<DeptTreeVo> getDeptTreeChildren(Integer pId) {
        List<DeptTreeVo> childrenDeptTreeList = new ArrayList<>();
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", pId);
        List<Department> departments = this.list(queryWrapper);
        for (Department department : departments) {
            DeptTreeVo deptTree = new DeptTreeVo();
            BeanUtils.copyProperties(department, deptTree);
            deptTree.setChildren(getDeptTreeChildren(deptTree.getId()));
            childrenDeptTreeList.add(deptTree);
        }
        return childrenDeptTreeList;
    }

}

